//
//  WBUserAccountViewModel.swift
//  Weibo
//
//  Created by xu on 2017/3/22.
//  Copyright © 2017年 xuantong. All rights reserved.
//

import UIKit

private let userAccount_Path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

class WBUserAccountViewModel: NSObject {
    
    //全局只有且只有一个登录用户 --创建单利对象
    
    static let shared:WBUserAccountViewModel = WBUserAccountViewModel()
    
    //需要持有一个模型对象 --> 处理数据
    var account: WBUserAccount?
    
    
    // 访客令牌
    var accessToken: String?{
        // 登录了
        if userLogin {
            return account?.access_token
        }
        // 反之
        return nil
    }
    
    
    
    //在对单例对象实例化的时候 就给调用loadUserAccount方法的返回值给account赋值
    private override init() {
        super.init()
        //当用户没有登录 但是单例对象已经实例化的时候 account没有值,并且以后都不会再赋值
        self.account = self.loafUserAccount()
    }
    
    
    //用户头像的 纯种的url对象
    var headURL: URL? {
        return URL(string: account?.avatar_large ?? "")
    }
    
    
    //判断用户是否过期
    var userLogin : Bool {
        
        if account?.access_token != nil && isExpires == false {
            
            return true
        }
        //默认过期
        
        return false
    }
    
    
    var isExpires: Bool {
        //是否过期 通过过期日期和当前日期比较
        if account?.expires_date?.compare(Date()) == .orderedDescending {
            return false
        }
        //默认过期
        return true
    }
    
    
    
    //请求用户授权token code finished授权结果
    func loadAccessToken(code:String,finished:@escaping (Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        
        let para = ["client_id":client_id,
                    "client_secret" : client_secret,
                    "grant_type" : "authorization_code",
                    "code" : code,
                    "redirect_uri" : redirect_uri]
        
        //网络请求工作
        WBNetworkTools.shared.request(method: .POST, urlString: urlString, paramters: para) { (res, error) in
            //执行失败的回调
            if error != nil {
                
                finished(false)
                
                return
            }
            //发起一个网络请求 -> 获取用户信息
            self.loadUserInfo(res as! [String : Any],loadUserInfoFinished: finished)
            
        }
        
        
    }
    //加载用户信息
    private func loadUserInfo (_ dict:[String:Any],loadUserInfoFinished :@escaping (Bool)->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        
        
        let token = dict["access_token"]!
        
        let uid = dict["uid"]!
        
        let para = ["access_token" : token,
                    "uid": uid]
        
        WBNetworkTools.shared.request(method: .GET, urlString: urlString, paramters: para) { (res, error) in
            
            //执行失败的回调
            if error != nil {
                loadUserInfoFinished(false)
                return
            }
            //登录成功.将信息保存在沙盒中
            var userInfoDict = res as! [String : Any]
            for(key,value)in dict{
                
                userInfoDict[key] = value
                
            }
            
            //存储用户登录信息  -> 将userInfoDict字典转模型
            let userAccount = WBUserAccount (dict :userInfoDict)
            //给单例对象的account 赋值
            self.account = userAccount
            
            self.saveUserAccount(account: userAccount)
            
            //当用户信息存储完毕之后 再执行成功的回调
            loadUserInfoFinished(true)
            
        }
        
        
    }
    
    //归档到沙盒
    private func saveUserAccount(account:WBUserAccount) {
        
        
        NSKeyedArchiver.archiveRootObject(account, toFile: userAccount_Path)
    }
    
    
    
    
    //解档
    func loafUserAccount()-> WBUserAccount? {
        
        let account = NSKeyedUnarchiver.unarchiveObject(withFile:userAccount_Path)
        if let acc = account as? WBUserAccount {
            return acc
            
        }
        
        
        return nil
        
    }
    
}



//MARK: 微博首页数据请求
extension WBNetworkTools {
    func homeLoadData(finished:@escaping(Any?,Error?)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //请求参数
        let params = ["access_token": WBUserAccountViewModel.shared.accessToken!]
        
        //发送请求
        request(method: HTTPMethod.GET, urlString: urlString, paramters: params, finished: finished)
    }
}
